<template>
  <el-form :model="pwdForm" :rules="rules" ref="pwdFormRef" label-width="100px">
    <!-- 原密码 -->
    <el-form-item label="原密码" prop="old_pwd">
      <el-input v-model="pwdForm.old_pwd" type="password" autocomplete="off"></el-input>
    </el-form-item>
    <!-- 新密码 -->
    <el-form-item label="新密码" prop="new_pwd">
      <el-input v-model="pwdForm.new_pwd" type="password" autocomplete="off"></el-input>
    </el-form-item>
    <!-- 确认密码 -->
    <el-form-item label="确认密码" prop="re_pwd">
      <el-input v-model="pwdForm.re_pwd" type="password" autocomplete="off"></el-input>
    </el-form-item>
    <!-- 按钮 -->
    <el-form-item>
      <el-button type="primary" @click="submitForm">修改密码</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { userUpdatePassService } from '../../api/user';
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore()
const pwdForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
});



// 表单引用
const pwdFormRef = ref(null);

const router = useRouter()
const submitForm = async () => {
  const valid = pwdFormRef.value.validate();
  if (valid) {
    await userUpdatePassService(pwdForm.value)
    await userStore.setToken('')
    await userStore.setUser({})
    ElMessage.success('修改成功')
    router.push('/login')
  }
}
// 校验规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (value.length < 6 || value.length > 15) {
    callback(new Error('密码长度应为6-15位'));
  } else {
    if (pwdForm.re_pwd !== '') {
      if (!pwdFormRef.value) return;
      pwdFormRef.value.validateField('re_pwd', () => null);
    }
    callback();
  }
};

const validateConfirmPass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== pwdForm.new_pwd) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const validateOldAndNewPass = (rule, value, callback) => {
  if (value === pwdForm.new_pwd) {
    callback(new Error('新密码不能与原密码相同'));
  } else {
    callback();
  }
};

const rules = reactive({
  old_pwd: [{ validator: validatePass, trigger: 'blur' },
  { validator: validateOldAndNewPass, trigger: 'blur' }],
  new_pwd: [{ validator: validatePass, trigger: 'blur' }],
  re_pwd: [{ validator: validateConfirmPass, trigger: 'blur' }]
});


// 重置表单
const resetForm = () => {
  pwdFormRef.value.resetFields();
};
</script>

<style lang="scss" scoped>
.el-input {
  width: 300px;
}
</style>
